package club.babyf.nativeai.demo.algorithm;

import java.util.ArrayList;
import java.util.List;

/**
 * _31_ZConvent.
 *
 * @author zhanglei.
 * @date 2025/8/8 22:06.
 * @description 字符串Z型转换.
 */
public class _31_ZConvent {

    public String zConvent(String s, int rows) {
        if (s == null || s.isEmpty() || rows == 1) {
            return s;
        }
        List<StringBuilder> realRows = new ArrayList<>();
        for (int i = 0; i < Math.min(s.length(), rows); i++) {
            realRows.add(new StringBuilder());
        }
        int curRow = 0;
        boolean goDowning = false;
        for (int i = 0; i < s.length(); i++) {
            realRows.get(curRow).append(s.charAt(i));
            if (curRow == 0 || curRow == realRows.size() - 1) {
                goDowning = !goDowning;
            }
            curRow += goDowning ? 1 : -1;
        }
        StringBuilder res = new StringBuilder();
        for (StringBuilder realRow : realRows) {
            res.append(realRow);
        }
        return res.toString();
    }

    public static void main(String[] args) {
        _31_ZConvent convent = new _31_ZConvent();
        String s = convent.zConvent("PAYPALISHIRING", 3);
        System.out.println(s);
    }

}
